import { useStore } from 'vuex'
import { computed } from 'vue'
import { setObjLocal } from '@/assets/js/localStore'

function useFavourite() {
  const store = useStore()

  const currentSong = computed(() => {
    return store.getters['play/currentSong']
  })

  const favouriteList = computed(() => {
    return store.state.play.favouriteList
  })

  const isFavourite = computed(() => {
    return (
      favouriteList.value.findIndex(item => item === currentSong.value.id) > -1
    )
  })

  const getFavouriteIcon = computed(() => {
    return isFavourite.value ? 'purple-heart-fill' : 'purple-heart'
  })

  function toggle(id) {
    if (isFavourite.value) {
      remove(currentSong.value.id)
    } else {
      add(currentSong.value.id)
    }
  }

  function remove(id) {
    const list = [...favouriteList.value]
    const index = list.findIndex(item => item === id)
    if (index > -1) {
      list.splice(index, 1)
      setObjLocal('favourite', list)
      store.commit('play/setFavouriteList', list)
    }
  }

  function add(id) {
    const list = [...favouriteList.value]
    const index = list.findIndex(item => item === id)
    if (index === -1) {
      list.push(id)
      setObjLocal('favourite', list)
      store.commit('play/setFavouriteList', list)
    }
  }

  return {
    getFavouriteIcon,
    toggle
  }
}

export default useFavourite
